<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-06-24
 * Time: 13:41
 */

namespace app\api\service\coupon;


use app\api\model\CouponUser;
use app\api\model\User;
use app\api\service\Token;
use app\lib\exception\ParameterException;
use think\Db;
use think\Exception;

class CouponOrderSer extends Token
{
    /**
     * 在构造函数里面把需要的数据都添加好
     * 1.获取优惠券与订单信息
     * 2.判断优惠券
     * 3.判断订单
     * 5.返回价格
     */

    // 优惠券信息
    private $couponUser;

    // 订单信息
    private $order;

    // 用户信息
    private $user;

    // 订单金额
    private $price;

    // 构造函数
    function __construct($coupon_id,$price)
    {
        $this->user = User::get(self::getCurrentUid());
        $this->couponUser = CouponUser::where('id',$coupon_id)->find();
        $this->price = $price;
    }

    // 入口方法
    public function entrance()
    {
        return $this->judgeCoupon();
    }

    // 判断优惠券
    private function judgeCoupon()
    {
        if(!$this->couponUser) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '优惠券为空'
                ]
            ]);
        }
        if($this->couponUser['user_id'] != $this->user['id']) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '此优惠券不是您的优惠券'
                ]
            ]);
        }
        $time = time();
        if($this->couponUser['start_time'] > $time) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '优惠券还未到使用时间'
                ]
            ]);
        }
        if($this->couponUser['end_time'] < $time) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '优惠券已过期'
                ]
            ]);
        }
        if($this->couponUser['surplus_times'] == 0) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '此优惠券已经使用'
                ]
            ]);
        }
        return $this->judgeOrder();
    }

    // 判断订单
    private function judgeOrder()
    {
        if($this->couponUser['amount_of_money_use'] > $this->price) {
            throw new ParameterException([
                'msg' => [
                    'coupon_order' => '此订单不满足次优惠券条件'
                ]
            ]);
        }
        return $this->updateCouponAndOrder();
    }

    // 更新优惠券与订单
    private function updateCouponAndOrder()
    {
        return round($this->couponUser['money']/$this->couponUser['usage_times'],2);
    }
}